<?php

class Soul_Request_Http_Identity {

    protected static $sessionKey = '__identity';
    protected $data = array('roles'=>array(), 'login'=>FALSE, 'name'=>'');

    public function __construct() {
        if($GLOBALS[RC]->getSession()->has(self::$sessionKey)){
            $this->data = unserialize($GLOBALS[RC]->getSession()->get(self::$sessionKey));
        }      
    }

    public function getName() {
        return $this->data['name'];
    }

    public function setName($value) {
        $this->data['name'] = $value;
        return $this;
    }

    public function isLogin() {
        return $this->data['login'] == TRUE;
    }

    public function getRoles() {
        return $this->data['roles'];
    }

    public function addRole($role) {
    	if(is_array($role)){
    		$this->data['roles'] = array_merge($this->data['roles'], $role);
    	}else{
        	$this->data['roles'][] = $role;
    	}
        return $this;
    }

    public function isInRole($code) {
        return in_array($code, $this->data['roles']);
    }

    public function isInAnyRole(array $codes) {
        if(count($codes) == 0){
            return TRUE;
        }
        foreach ($codes as $code) {
            if ($this->isInRole($code)) {
                return TRUE;
            }
        }
        return FALSE;
    }

    public function login() {
        $this->data['login'] = TRUE;
        $GLOBALS[RC]->getSession()->set(self::$sessionKey, serialize($this->data));
    }

    public function logout() {
        $this->data['login'] = FALSE;
        $GLOBALS[RC]->getSession()->remove(self::$sessionKey);
    }
}